<?php
JunctionFileCabinet::using("Junction_Db_Creole_Adapter");
JunctionFileCabinet::using("Junction_Db_Creole_Service");

class Test_Junction_Db_Creole_Service extends UnitTestCase {
	
	private $_insertQuery = "INSERT INTO users (user_id, email, name, password, date_added) VALUES (null, 'foo@bar', 'foobar', 'password', 1189392979)";
	private $_insertPreparedQuery = "INSERT INTO users (user_id, email, name, password, date_added) VALUES (?, ?, ?, ?, ?)";
	
	private $_updateQuery;
	private $_updatePreparedQuery = "UPDATE users SET date_added = ? WHERE user_id = ?";
	
	private $_selectQuery = "SELECT * FROM users";
	private $_selectPreparedQuery = "SELECT * FROM users WHERE date_added < ?";
	
	public function __construct() {
		$this->_updateQuery = "UPDATE users SET date_added = " . time() . " WHERE user_id = 1";
	}
	
	/**
	 * Database service
	 *
	 * @var Junction_Db_Common_Service
	 */
	private $_dbh;
	
	public function testConstruct() {
		$driver = "sqlite";
			$host = null;
			$database = Test_Database_Catalog::fetch("test.sdb");
			$user = null;
			$password = null;
			
		$driver = "mysql";
			$host = "localhost";
			$database = "JunctionTest";
			$user = "JunctionUser";
			$password = "junction";
			
		$adapter = new Junction_Db_Creole_Adapter($driver,
			$host,
			$database,
			$user,
			$password);
			
		$this->_dbh = new Junction_Db_Creole_Service($adapter);
		$this->pass();
	}
	
	public function testInsert() {
		try {
			$this->assertTrue($this->_dbh->save($this->_insertQuery));
			$this->assertTrue($this->_dbh->lastInsertId() > 0);
		} catch (Junction_Db_Common_Exception $e) {
			$this->fail();
		}
		
		try {
			$this->assertTrue($this->_dbh->save($this->_insertPreparedQuery, array(null, 'foo@bar', 'foobar', 'password', 1189392979)));
			$this->assertTrue($this->_dbh->lastInsertId() > 0);
		} catch (Junction_Db_Common_Exception $e) {
			$this->fail();
		}
	}
	
	public function testUpdate() {
		try {
			$this->assertTrue($this->_dbh->save($this->_updateQuery));
			$this->assertTrue($this->_dbh->affectedRows() > 0);
		} catch (Junction_Db_Common_Exception $e) {
			$this->fail();
		}
		
		try {
			$this->assertTrue($this->_dbh->save($this->_updatePreparedQuery, array(time() + 20, 1)));
			$this->assertTrue($this->_dbh->affectedRows() > 0);
		} catch (Junction_Db_Common_Exception $e) {
			$this->fail();
		}
	}
	
	public function testSelect() {
		try {
			$results = $this->_dbh->select($this->_selectQuery);
			$rows = array();
			foreach ($results as $row) {
				$rows[] = $row;
			}
			$this->assertTrue(count($rows) > 0);
			
		} catch (Junction_Db_Common_Exception $e) {
			$this->fail();
		}
		
		try {
			$results = $this->_dbh->select($this->_selectPreparedQuery, array(time()));
			$rows = array();
			foreach ($results as $row) {
				$rows[] = $row;
			}
			$this->assertTrue(count($rows) > 0);
		} catch (Junction_Db_Common_Exception $e) {
			$this->fail();
		}
	}
}
?>